<?php
	/**
	 * 登录
	 */
    class Login extends APIBase {
		
		public $tag = "Login";
		public $isLogin = false;
		
		
		public function before() {
			$this->initMysql();
			$this->initCacheRedis();
			$this->inithttp();
			return true;
		}
	
		public function logic() {
			if (!isset($this->param['user'])) {
				$this->returnError(310, "请输入用户名称");
			} 
			
			if (!isset($this->param['password'])) {
				$this->returnError(311, "请输入密码");
			}

			$user = strtolower($this->param['user']);		
            			
			$row = $this->mysql->select("player", "*", array('user' => $user));
			//$row = $this->mysql->query("select * from player where user=".$user);
			
			if (count($row) == 0) {
				$this->returnError(312, '用户名称错误！');
			} elseif (count($row) > 1) {
				$this->e("{$user} repeat");
				$this->returnError(500, "用户名称重复！");
			}

			$password = md5($this->param['password'].$row[0]['salt']);
			if ($password != $row[0]['password']) {
				$this->returnError(312, '用户密码错误！');
			}
			
			if ($row[0]['status'] == 0){
				$this->returnError(310,"用户已经被禁用！");
			}
			//验证绑带机器码
			/*
			if($row[0]['bindpuid']!=''){
				
				if(trim($this->param['puid']) != trim($row[0]['bindpuid']))
					$this->returnError(699, "登录机器绑定机器码不一致！");
				
			}
			*/
			
			$uid = $row[0]['id'];			 
			$this->initDataRedis($uid);		

			$isExists = $this->data_redis->exists("hu:{$uid}");
			$player = $this->data_redis->hMGet("hu:{$uid}", array('id', 'user','skey'));
			//$isExists = 0;
			if (!$isExists || $player['id']==null || $player['user'] == null) {
                //会员数据存到redis数据库
				$this->data_redis->hMset("hu:{$uid}", $row[0]);
			}
			
			//判断玩家是否有背包数据
                $backpackCount = $this->cache_redis->keys("hbackpack:".$uid.":*"); 
                if(count($backpackCount)<=0){//如果玩家redis不存在背包 
					//判断数据库是否有玩家背包数据 
					$result = $this->mysql->find("select * from backpack where uid =".$uid);
					if(!empty($result)){//如果数据库存在背包,则把数据库背包数据写入redis 
						$r = array(); 
							foreach ($result as $key=>$val) { 
								$r = array(); 
								$r['uid'] = (int)$val['uid']; 
								$r['propid'] = (int)$val['propid'];
								$r['count'] = (int)$val['count'];
								$r['createtime'] = (int)$val['createtime'];
								$r['status'] =(int)$val['status'];
								$this->cache_redis->hMset("hbackpack:".$uid.":".$val['propid'],$r);
							}
					}else{
					    $data = array('uid'=>$uid,'propid'=>1,'count'=>10,'createtime'=>time(),'status'=>1);
						$this->cache_redis->hMset("hbackpack:".$uid.":".'1',$data);
					
					}
				}
				
				//判断玩家是否有邮件数据
				$hemailbyuser = $this->cache_redis->keys("hemailbyuser:".$uid.":*");
			    if(count($hemailbyuser)<=0){//如果玩家redis不存在背包
			    //判断数据库是否有玩家背包数据
				    $result = $this->mysql->find("select * from emailbyuser where uid =".$uid);
				    if(!empty($result)){//如果数据库存在背包,则把数据库背包数据写入redis
				            foreach ($result as $key=>$val) {
		                        $r = array();
		                        $r['uid'] = (int)$val['uid'];
		                        $r['mid'] = (int)$val['mid'];
                                $r['is_read'] = (int)$val['is_read'];
                                $r['is_receive'] = (int)$val['is_receive'];
                                $r['send_date'] = (int)$val['send_date'];
                                $r['update_date'] = (int)$val['update_date'];	
                                $r['sender'] = (string)$val['sender'];									
		                        $this->cache_redis->hMset("hemailbyuser:".$uid.":".$val['id'],$r);
	                        }
			        }
			    }
				
			    //判断玩家是否有匹配场战绩数据
				$isExists_match = $this->data_redis->exists("hu:".$uid.":match"); 
                if(!$isExists_match){
					$result = $this->mysql->find("select * from player_game where user_id=$uid");
					if(!empty($result)){//如果数据库存在匹配场数据,则写入redis 
						$r = array();
						foreach ($result as $key=>$val) {         
							$r['user_id'] = (int)$val['user_id']; 
							$r['win_count'] = (int)$val['win_count'];
							$r['lose_count'] = (int)$val['lose_count'];
							$r['winning_streak'] = (int)$val['winning_streak'];
							$r['highest_winning_streak'] = (int)$val['highest_winning_streak'];
						}
						$this->data_redis->hMset("hu:$uid:match",$r);
					}else{
						$this->data_redis->hMset("hu:$uid:match",array('user_id'=>$uid,'win_count'=>0,'lose_count'=>0,'winning_streak'=>0,'highest_winning_streak'=>0));
					}
                }


			
			//判断是否要弹出签到层
			//$this->sign_count($uid);
			
			//判断是否分享
			/*
			$row_ = $this->mysql->select("sharecount",'*',array('sid'=>$uid));
			if(empty($row_)){
				$this->data_redis->hset("hu:{$uid}", "hadinvited", 0);
			}else{
				$this->data_redis->hset("hu:{$uid}", "hadinvited", 1);
			}
			*/
			
			//$this->continuous_landing($uid);//计算连续登陆
			$salt = $this->data_redis->hGet("hu:{$uid}", 'salt');
			$now = time();

			$skey = md5($now . $salt);
			//抢登
			/*
			if($isExists){
			    $url = 'http://'.Config::$ip_server_config['ip'].':'.Config::$ip_server_config['myport'].'/pushsrv?action=login&receiver='.$uid.'&param={"skey":"'.$player['skey'].'"}';
				if(!$this->http->get($url)){
				    	//$this->returnError(599, "抢登异常！");
				}
				
			} 
			*/
			//获取登录用户ip
			$ip = $this->getRealIp();

			//重置玩家session skey，给测试账户设置money字段并初始化
			$this->data_redis->hMset("hu:$uid", array("update_time" => $now, "heartbeat_at" => $now,"skey" => $skey, "login_ip" => $ip)); 
			$user_info = $this->data_redis->hMget("hu:$uid", array('point',
					'user', 'name', 'sex',  'skey','login_days', 'is_get_login_reward','password','avater_url','is_vip','payment','accid'
			));
		   
            
			//判断vip
			if($user_info['is_vip']){
				$user_info['is_vip']=1;
			}
			/*
			if((int)$user_info['is_vip']&& time()<(int)$user_info['vip_time']){
			  
			  $remaining = ceil(((int)$user_info['vip_time']-time())/86400);
			  $user_info['remaining'] = $remaining;
			  	
			 //会员登录通知
			  $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=Marquee&receiver=all&param={"user":"_'.$user_info['name'].'","type":1}';
			  if(!$this->http->get($url)){
				   // $this->returnError(599, "通知异常！");
			  }
			    
			}else{
			 //
			 /* $this->data_redis->hMset("hu:$uid",array('is_vip'=>0)); 	
			  $user_info['remaining'] = 0;
			  $user_info['is_vip'] = 0;		
			}
			*/
            //获取背包局数卡
			$round_card_num = $this->cache_redis->hGet("hbackpack:".$uid.":1",'count');
			$user_info['uid'] = (int)$uid;
			$user_info['accid'] = (int)$user_info['accid'];
			$user_info['sex'] = (int)$user_info['sex'];
			$user_info['login_days'] = (int)$user_info['login_days'];
			$user_info['is_get_login_reward'] = (int)$user_info['is_get_login_reward'];
			$user_info['is_vip'] = (int)$user_info['is_vip'];
			$user_info['password'] = $password;
			$user_info['avater_url'] = $user_info['avater_url']?$user_info['avater_url']:'';
			//$user_info['bindpuid'] = $user_info['bindpuid']?'true':'false';
			$user_info['payment'] = $user_info['payment'];
			$user_info['ip'] = Config::$ip_server_confing['ip'];
			$user_info['port'] = Config::$ip_server_confing['port'];
			$user_info['round_card_num'] = (int)$round_card_num;
			$user_info['point'] = $user_info['point'];
			$this->returnData($user_info);
		}
	
		/**
		 * 连续登录
		 */
		private function continuous_landing($uid) {
		//date_default_timezone_set('UTC');
		$ts = time();
		$update_time = $this->data_redis->hGet("hu:{$uid}", 'update_time');// 上次登录时间
		$login_days =  $this->data_redis->hGet("hu:{$uid}", 'login_days');
		if ($update_time <= $ts) {
			//$this->data_redis->hset("hu:{$uid}", "lottery_count", 0); //lottery times
			if ($update_time > ($ts - 86400)) {
				//$this->data_redis->hincrBy("hu:{$uid}", "login_days", 1);
				$this->data_redis->hset("hu:{$uid}", "is_get", 1);
				if((int)$login_days==7){
					$this->data_redis->hset("hu:{$uid}", "login_days", 0);
				}
			} else {
				$this->data_redis->hMset("hu:{$uid}", array("login_days" => 0, "is_get" => 0));
			}
		 }
	    }
		
	    /**
		 * 是否弹出签到层
		 */
	    private function sign_count($uid){
			$flag = 0;//不弹出签名层
			$ts = time();
		    $signlist = $this->cache_redis->hMGet("hSign:{$uid}", array('uid','is_sign','signdate'));
		    //判断是否签到过
			if(!$signlist['uid']){
				$flag = 1;
				$this->data_redis->hset("hu:{$uid}", "flag", 1);
			}else{
				//判断是否在同一天签到
				if($signlist['is_sign']){
					$flag = 0;
					$this->data_redis->hset("hu:{$uid}", "flag", 0);
				}elseif($signlist['is_sign']==0 && (strtotime(date("Y-m-d",$ts))-strtotime(date("Y-m-d",$signlist['signdate'])))/24/3600 <= 1){//判断是否连天签到
					$flag = 1;
					$this->data_redis->hset("hu:{$uid}", "flag", 1);
				}elseif($signlist['is_sign']==0 && (strtotime(date("Y-m-d",$ts))-strtotime(date("Y-m-d",$signlist['signdate'])))/24/3600 > 1){//不是连天签到
					$flag = 1;
					$this->data_redis->hset("hu:{$uid}", "flag", 1);
				}
				
			}
	    }
	   
	   
    	public function after() {
    		$this->deinitDataRedis();
			$this->deinitCacheRedis();
			$this->deinitMysql();
			$this->deinithttp();
		}
    }
?>
